<template>
  <div class="region-selector">
    <div class="tab-address-nav flex" ref="tabAddressNavRef">
      <!-- 省份选择 -->
      <div
        class="item flex items-center mr-5 cursor-pointer"
        :class="{ active: tabIndex == 0 }"
        @click="handleTabClick($event, 0)"
      >
        <span class="mr-1 text-gray-700 text-3.5 font-600">{{ selectedProvince }} </span>
        <el-icon><ArrowDown /></el-icon>
      </div>
      <div
        v-show="!isMunicipality"
        class="item flex items-center mr-5 cursor-pointer"
        :class="{ active: tabIndex == 1 }"
        @click="handleTabClick($event, 1)"
      >
        <span class="mr-1 text-gray-700 text-3.5 font-600">{{ selectedCity }} </span>
        <el-icon><ArrowDown /></el-icon>
      </div>
      <div
        class="item flex items-center mr-5 cursor-pointer"
        :class="{ active: tabIndex == 2 }"
        @click="handleTabClick($event, 2)"
      >
        <span class="mr-1 text-gray-700 text-3.5 font-600">{{ selectedDistrict }} </span>
        <el-icon><ArrowDown /></el-icon>
      </div>
      <div
        v-show="!isMunicipality"
        class="item flex items-center mr-5 cursor-pointer"
        :class="{ active: tabIndex == 3 }"
        @click="handleTabClick($event, 3)"
      >
        <span class="mr-1 text-gray-700 text-3.5 font-600">{{ selectedTownship }} </span>
        <el-icon><ArrowDown /></el-icon>
      </div>
    </div>
    <div class="area-list">
      <div class="tab-content bg-gray-50 py-2" ref="tabContentRef">
        <div class="tab-item" v-show="tabIndex == 0">
          <el-scrollbar height="230px">
            <div class="flex flex-wrap mt-2">
              <div
                class="item cursor-pointer mr-2 mb-2 px-2 py-1.5 border-rounded"
                style="min-width: 75px"
                v-for="(child, cIndex) in provinces"
                :key="cIndex"
                :class="{ active: selectedProvince === child.name }"
                @click="handleItemClick($event, 0, child)"
              >
                <span class="text-3.5">{{ child.name }}</span>
              </div>
            </div>
          </el-scrollbar>
        </div>
        <div class="tab-item" v-show="tabIndex == 1 && !isMunicipality">
          <el-scrollbar height="230px">
            <div class="flex flex-wrap mt-2">
              <div
                class="item cursor-pointer mr-2 mb-2 px-2 py-1.5 border-rounded"
                style="min-width: 75px"
                v-for="(child, cIndex) in cities"
                :key="cIndex"
                :class="{ active: selectedCity === child.name }"
                @click="handleItemClick($event, 1, child)"
              >
                <span class="text-3.5">{{ child.name }}</span>
              </div>
            </div>
          </el-scrollbar>
        </div>
        <div class="tab-item" v-show="tabIndex == 2">
          <el-scrollbar height="230px">
            <div class="flex flex-wrap mt-2">
              <div
                class="item cursor-pointer mr-2 mb-2 px-2 py-1.5 border-rounded"
                style="min-width: 75px"
                v-for="(child, cIndex) in districts"
                :key="cIndex"
                :class="{ active: selectedDistrict === child.name }"
                @click="handleItemClick($event, 2, child)"
              >
                <span class="text-3.5">{{ child.name }}</span>
              </div>
            </div>
          </el-scrollbar>
        </div>
        <div class="tab-item" v-show="tabIndex == 3 && !isMunicipality">
          <el-scrollbar height="230px">
            <div class="flex flex-wrap mt-2">
              <div
                class="item cursor-pointer mr-2 mb-2 px-2 py-1.5 border-rounded"
                style="min-width: 75px"
                v-for="(child, cIndex) in towns"
                :key="cIndex"
                :class="{ active: selectedTownship === child.name }"
                @click="handleItemClick($event, 3, child)"
              >
                <span class="text-3.5">{{ child.name }}</span>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, onMounted } from "vue";
import { Close, ArrowDown } from "@element-plus/icons-vue";
import {
  getProvinces,
  getPrefectures,
  getCounties,
  getCodeByProvinceName,
} from "china-region";
import type { Region } from "china-region";

// 定义Props接口
interface RegionProps {
  province?: string;
  city?: string;
  district?: string;
  township?: string;
}

const props = withDefaults(defineProps<RegionProps>(), {
  province: "",
  city: "",
  district: "",
});

// 定义Emits
const emit = defineEmits<{
  (e: "update:province", value: string): void;
  (e: "update:city", value: string): void;
  (e: "update:district", value: string): void;
  (e: "change", value: RegionOutput): void;
}>();

// 定义输出类型
interface RegionOutput {
  province: string;
  city: string;
  district: string;
  fullCode?: string;
}


// 直辖市列表
const municipalities = ["北京市", "天津市", "上海市", "重庆市"];
const tabIndex = ref(0);
// 响应式数据
const provinces = ref<Region[]>(getProvinces());
const cities = ref<Region[]>([]);
const districts = ref<Region[]>([]);
const towns = ref<Region[]>([
  {
    name: "东城",
    code: "110101",
  },
  {
    name: "西城",
    code: "110102",
  },
  {
    name: "南城",
    code: "110103",
  },
  {
    name: "北城",
    code: "110104",
  },
  {
    name: "中城",
    code: "110105",
  },
]);
console.log(provinces);

const selectedProvince = ref(props.province || "");
const selectedCity = ref(props.city || "");
const selectedDistrict = ref(props.district || "");
const selectedTownship = ref(props.township || "");

// 计算是否为直辖市
const isMunicipality = computed(() => {
  console.log("属性计算：", selectedProvince.value);
  return municipalities.includes(selectedProvince.value);
});

// 获取乡镇数据（模拟，实际需替换为真实接口）
const getTownshipData = (districtName: string): Region[] => {
  // 这里应替换为真实的乡镇数据接口调用
  return [
    { name: "东城", code: "110101" },
    { name: "西城", code: "110102" },
    { name: "南城", code: "110103" },
  ];
};
const handleTabClick = (e: any, index: number) => {
  tabIndex.value = index;
};
const handleItemClick = (e: any, index: number, item: any) => {
  console.log(index, item);
  switch (index) {
    case 0:
      if (municipalities.includes(item.name)) {
        tabIndex.value = 2;
      } else {
        tabIndex.value = index + 1;
      }
      selectedProvince.value = item.name;
      break;
    case 1:
      tabIndex.value = index + 1;
      selectedCity.value = item.name;
      break;
    case 2:
      if (!isMunicipality.value) {
        tabIndex.value = index + 1;
      }
      selectedDistrict.value = item.name;
      break;
    case 3:
      selectedTownship.value = item.name;
      break;
  }
  console.log("当前区域：", tabIndex.value);
};
// 监听省份变化
watch(selectedProvince, (newProvince) => {
  // 重置下级选择
  selectedCity.value = "";
  selectedDistrict.value = "";
  cities.value = [];
  districts.value = [];
  towns.value = [];

  console.log("省份变化：", newProvince);
  if (newProvince) {
    // 获取省份代码
    const provinceCode = getCodeByProvinceName(newProvince);
    console.log(provinceCode, isMunicipality.value);
    if (isMunicipality.value) {
      // 如果是直辖市，直接加载区县数据
      districts.value = getCounties(provinceCode);
      console.log(districts.value);
      // 如果props中有默认区县值，尝试选中
      if (props.district) {
        const targetDistrict = districts.value.find(
          (district) => district.name === props.district
        );
        if (targetDistrict) selectedDistrict.value = props.district;
      } else {
        selectedDistrict.value = districts.value[0]?.name || "";
      }
    } else {
      // 非直辖市，加载城市数据
      cities.value = getPrefectures(provinceCode);

      // 如果props中有默认城市值，尝试选中
      if (props.city) {
        const targetCity = cities.value.find((city) => city.name === props.city);
        if (targetCity) selectedCity.value = props.city;
      } else {
        selectedCity.value = cities.value[0]?.name || "";
      }
    }
  }

  emit("update:province", newProvince);
  // 如果是直辖市，城市值设为与省份相同
  emit("update:city", isMunicipality.value ? newProvince : "");
  emitChangeEvent();
});

// 监听城市变化
watch(selectedCity, (newCity) => {
  selectedDistrict.value = "";
  districts.value = [];

  if (newCity && !isMunicipality.value) {
    // 查找城市代码并加载区县数据
    const cityCode = cities.value.find((item) => item.name === newCity)?.code;
    if (cityCode) {
      districts.value = getCounties(cityCode);
    }

    // 如果props中有默认区县值，尝试选中
    if (props.district) {
      const targetDistrict = districts.value.find(
        (district) => district.name === props.district
      );
      if (targetDistrict) selectedDistrict.value = props.district;
    } else {
      selectedDistrict.value = districts.value[0]?.name || "";
    }
  }

  emit("update:city", isMunicipality.value ? selectedProvince.value : newCity);
  emitChangeEvent();
});

// 监听区县变化
watch(selectedDistrict, (newDistrict) => {
  console.log("区县变化：", newDistrict);
  if (newDistrict) {
    towns.value = getTownshipData(newDistrict);
    if (props.township) {
    } else {
      selectedTownship.value = towns.value[0]?.name || "";
    }
  }
  emit("update:district", newDistrict);
  emitChangeEvent();
});

// 监听props变化，更新选中值
watch(
  () => props.province,
  (newVal) => {
    if (newVal) selectedProvince.value = newVal;
  }
);

watch(
  () => props.city,
  (newVal) => {
    if (newVal && cities.value.some((city) => city.name === newVal)) {
      selectedCity.value = newVal;
    }
  }
);

watch(
  () => props.district,
  (newVal) => {
    if (newVal && districts.value.some((district) => district.name === newVal)) {
      selectedDistrict.value = newVal;
    }
  }
);

// 发出变化事件
function emitChangeEvent() {
  const output: RegionOutput = {
    province: selectedProvince.value,
    city: isMunicipality.value ? selectedProvince.value : selectedCity.value,
    district: selectedDistrict.value,
  };

  emit("change", output);
}

// 计算完整地区信息
const fullRegion = computed(() => {
  return `中国,${selectedProvince.value},${
    isMunicipality.value ? "" : selectedCity.value
  },${selectedDistrict.value}`;
});

onMounted(() => {
  // 初始化时，尝试选中默认值
  if (props.province) {
    selectedProvince.value = props.province;
  } else {
    selectedProvince.value = provinces.value[0].name;
  }
});

// 暴露方法和数据给父组件
defineExpose({
  selectedProvince,
  selectedCity,
  selectedDistrict,
  fullRegion,
  isMunicipality,
  clearAll: () => {
    selectedProvince.value = "";
    selectedCity.value = "";
    selectedDistrict.value = "";
  },
});
</script>

<style scoped>
.tab-address-nav {
  .item {
    min-width: 100px;
    height: 35px;
    padding: 5px 10px;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    transition: all 0.3s ease-in-out;
    &.active {
      background-color: #f5f5f591;
    }
  }
}
.area-list {
  .item {
    &.active {
      border: 1px solid #ff0000da;
      background-color: #fd474723;
      color: #e90707;
    }
    &:hover {
      background-color: #f5f5f5;
      color: #f00202;
    }
  }
}
</style>
